<?php
/**
 * Created by PhpStorm.
 * User: CY
 * Date: 2018/3/27
 * Time: 15:24
 */

namespace app\api\service;


use app\api\model\User;
use app\lib\exception\OrderException;
use app\lib\exception\UserException;

class DeliveryMessage extends WxMessage
{
    // 订单发货提醒模板id
    const DELIVERY_MSG_ID = '8zRdTxQf2g8HEbPbqE1ahLRGBzd1DLWX7U451n_D0TI';

    public function sendDeliveryMessage($order,$tplJumpPage = ''){
        if(!$order){
            throw new OrderException();
        }

        $this->tplID = self::DELIVERY_MSG_ID;
        $this->formID = $order->prepay_id;
        $this->page = $tplJumpPage;
        $this->prepareMessageData();
        $this->emphasisKeyWord = 'keyword3.DATA';
        return parent::sendMessage($this->getUserOpenID($order->user_id));
    }

    /**
     * 模板消息包含的数据
     * @param $order
     */
    private function prepareMessageData($order){
        $data = [
            'keyword1' => [
                'value' => '顺丰速运'
            ],
            'keyword2' => [
                'value' => date('Y-m-d H:i',time())
            ],
            'keyword3' => [
                'value' => $order->snap_name
            ],
            'keyword4' => [
                'value' => '阿羊商城'
            ],
            'keyword5' => [
                'value' => $order->snap_address
            ],
            'keyword6' => [
                'value' => $order->order_no
            ],
            'keyword7' => [
                'value' => '66666666666'
            ]
        ];
        $this->data = $data;
    }

    /**
     * 获取用户openid
     * @param $uid
     * @return mixed
     * @throws UserException
     */
    private function getUserOpenID($uid){
        $user = User::get($uid);
        if(!$user){
            throw new UserException();
        }else{
            return $user->openid;
        }
    }
}